<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
        }
        #sidebar {
            width: 200px;
            background: #2c3e50;
            color: white;
            padding: 20px;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
        }
        #sidebar h2 {
            font-size: 18px;
            margin-bottom: 20px;
        }
        #sidebar ul {
            list-style: none;
            padding: 0;
        }
        #sidebar ul li {
            margin-bottom: 10px;
        }
        #sidebar ul li button {
            width: 100%;
            padding: 10px;
            background: #34495e;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #sidebar ul li button:hover {
            background: #1abc9c;
        }
        #chat-container {
            flex: 1;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin: 20px;
        }
        #username-container {
            display: none;
            align-items: center;
            margin-bottom: 10px;
        }
        #username-container label {
            margin-right: 10px;
        }
        #username-container span {
            font-weight: bold;
        }
        #messages {
            height: 400px;
            overflow-y: scroll;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 20px;
        }
        #messages div {
            padding: 5px 0;
        }
        #message-input {
            display: flex;
        }
        #message-input input[type="text"] {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
        }
        #message-input button {
            padding: 10px;
            background: #007BFF;
            color: white;
            border: none;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }
        #message-input button:hover {
            background: #0056b3;
        }
        #login-container, #register-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        #login-container input[type="text"], #login-container input[type="password"],
        #register-container input[type="text"], #register-container input[type="password"] {
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        #login-container button, #register-container button {
            padding: 10px;
            background: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #login-container button:hover, #register-container button:hover {
            background: #0056b3;
        }
        #change-password-container {
            display: none;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        #change-password-container input[type="password"] {
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        #change-password-container button {
            padding: 10px;
            background: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #change-password-container button:hover {
            background: #0056b3;
        }
    </style>
</head>
<body>
    <div id="login-container">
        <h2>登录聊天室</h2>
        <input type="text" id="login-username" placeholder="用户名" />
        <input type="password" id="login-password" placeholder="密码" />
        <button onclick="login()">登录</button>
        <button onclick="showRegister()">注册</button>
        <div id="login-message" style="color: red;"></div>
    </div>

    <div id="register-container" style="display: none;">
        <h2>注册新账户</h2>
        <input type="text" id="register-username" placeholder="用户名" />
        <input type="password" id="register-password" placeholder="密码" />
        <button onclick="register()">注册</button>
        <button onclick="showLogin()">返回登录</button>
        <div id="register-message" style="color: green;"></div>
    </div>

    <div id="sidebar" style="display: none;">
        <h2>选择聊天室</h2>
        <ul>
            <li><button onclick="changeRoom('主聊天室')">主聊天室</button></li>
            <li><button onclick="changeRoom('吃货世界')">吃货世界</button></li>
            <li><button onclick="changeRoom('财经频道')">财经频道</button></li>
        </ul>
        <button id="change-password-button" onclick="showChangePassword()">修改密码</button>
    </div>
    <div id="chat-container" style="display: none;">
        <div id="username-container">
            <label for="username">用户名:</label>
            <span id="username-display"></span>
        </div>
        <h2 id="chat-room-title">主聊天室</h2>
        <div id="messages"></div>
        <div id="message-input">
            <input type="text" id="message" placeholder="输入消息..." />
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>

    <div id="change-password-container">
        <h2>修改密码</h2>
        <input type="password" id="old-password" placeholder="旧密码" />
        <input type="password" id="new-password" placeholder="新密码" />
        <button onclick="changePassword()">提交</button>
        <button onclick="hideChangePassword()">取消</button>
        <div id="change-password-message" style="color: red;"></div>
    </div>

    <script>
        const ws = new WebSocket('ws://localhost:12345');
        if (!ws) {
            alert('您的浏览器不支持 WebSocket，请更换浏览器后重试！');
        }
        let username = '';
        let currentRoom = '主聊天室';
        const usernameContainer = document.getElementById('username-container');
        const chatRoomTitle = document.getElementById('chat-room-title');
        const changePasswordButton = document.getElementById('change-password-button');
        const changePasswordContainer = document.getElementById('change-password-container');
        const changePasswordMessage = document.getElementById('change-password-message');

        ws.onmessage = function(event) {
            const data = JSON.parse(event.data);
            const loginMessage = document.getElementById('login-message');
            const registerMessage = document.getElementById('register-message');
            if (data.type === 'error') {
                if (data.message.includes('用户名已存在')) {
                    registerMessage.style.color = 'red';
                    registerMessage.innerText = data.message;
                } else {
                    loginMessage.innerText = data.message;
                }
            } else if (data.type === 'system' || data.type === 'history' || data.type === 'message') {
                const messages = document.getElementById('messages');
                const messageDiv = document.createElement('div');
                if (data.type === 'history' || data.type === 'message') {
                    messageDiv.textContent = `${data.sender}: ${data.message}`;
                } else if (data.type === 'system') {
                    messageDiv.textContent = data.message;
                }
                messages.appendChild(messageDiv);
                messages.scrollTop = messages.scrollHeight;
            } else if (data.type === 'login_success') {
                // 显示聊天室界面
                document.getElementById('login-container').style.display = 'none';
                document.getElementById('register-container').style.display = 'none';
                document.getElementById('sidebar').style.display = 'block';
                document.getElementById('chat-container').style.display = 'block';
                setUsername(data.username);
                loginMessage.innerText = '登录成功！';
                loginMessage.style.color = 'green';
                changePasswordButton.style.display = 'block';
            } else if (data.type === 'register_success') {
                registerMessage.style.color = 'green';
                registerMessage.innerText = '注册成功，请登录！';
            } else if (data.type === 'change_password_success') {
                changePasswordMessage.style.color = 'green';
                changePasswordMessage.innerText = '密码修改成功！';
                setTimeout(hideChangePassword, 2000);
            } else if (data.type === 'change_password_error') {
                changePasswordMessage.innerText = data.message;
            }
        };

        function setUsername(name) {
            username = name;
            document.getElementById('username-display').textContent = username;
            usernameContainer.style.display = 'flex';
        }

        function sendMessage() {
            if (!username) {
                alert('请先设置用户名！');
                return;
            }
            const input = document.getElementById('message');
            const text = input.value.trim();
            if (text) {
                ws.send(JSON.stringify({ action: 'message', message: text }));
                input.value = '';
            }
        }

        function changeRoom(room) {
            currentRoom = room;
            chatRoomTitle.textContent = room;
            document.getElementById('messages').innerHTML = ''; // 清空消息
            ws.send(JSON.stringify({ action: 'change_room', room: room }));
        }

        function login() {
            const inputUsername = document.getElementById('login-username').value.trim();
            const inputPassword = document.getElementById('login-password').value.trim();
            if (inputUsername && inputPassword) {
                ws.send(JSON.stringify({ action: 'login', username: inputUsername, password: inputPassword }));
            } else {
                alert('请输入用户名和密码');
            }
        }

        function register() {
            const inputUsername = document.getElementById('register-username').value.trim();
            const inputPassword = document.getElementById('register-password').value.trim();
            if (inputUsername && inputPassword) {
                ws.send(JSON.stringify({ action: 'register', username: inputUsername, password: inputPassword }));
            } else {
                alert('请输入用户名和密码');
            }
        }

        function showLogin() {
            document.getElementById('register-container').style.display = 'none';
            document.getElementById('login-container').style.display = 'flex';
        }

        function showRegister() {
            document.getElementById('login-container').style.display = 'none';
            document.getElementById('register-container').style.display = 'flex';
        }

        function showChangePassword() {
            changePasswordContainer.style.display = 'flex';
        }

        function hideChangePassword() {
            changePasswordContainer.style.display = 'none';
            changePasswordMessage.innerText = '';
            document.getElementById('old-password').value = '';
            document.getElementById('new-password').value = '';
        }

        function changePassword() {
            const oldPassword = document.getElementById('old-password').value.trim();
            const newPassword = document.getElementById('new-password').value.trim();
            if (oldPassword && newPassword) {
                ws.send(JSON.stringify({ action: 'change_password', old_password: oldPassword, new_password: newPassword }));
            } else {
                changePasswordMessage.innerText = '请输入旧密码和新密码';
            }
        }

        ws.onopen = function() {
            // 检查登录状态
            const loggedIn = localStorage.getItem('chat-logged-in');
            const storedUsername = localStorage.getItem('chat-username');
            if (loggedIn && storedUsername) {
                setUsername(storedUsername);
                document.getElementById('login-container').style.display = 'none';
                document.getElementById('sidebar').style.display = 'block';
                document.getElementById('chat-container').style.display = 'block';
                changePasswordButton.style.display = 'block';
            }
        };
    </script>
</body>
</html>
